package cs;

import handler.ConnectHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import vip.ipav.log.util.LoggerTools;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class ConnectExample {
    private static final Channel CHANNEL_FROM_SOMEWHERE = new NioSocketChannel();

    /**
     * Listing 1.3 Asynchronous connect
     *
     * Listing 1.4 Callback in action
     * */
    public static void connect(String ip,int port) throws InterruptedException {
        //设置连接的相关方式
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(ip, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch)
                            throws Exception {
                        ch.pipeline().addLast(
                                new ConnectHandler());
                    }
                });
        //获取连接，并发送数据
        ChannelFuture f = null;
        try {
            LoggerTools.getConsoleLogger().info("开始建立连接！");
            f = b.connect().sync();
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) {
                    LoggerTools.getConsoleLogger().info("开始发送数据,{}",future.isSuccess());
                    if (future.isSuccess()) {
                        ByteBuf buffer = Unpooled.copiedBuffer(
                                "Hello", Charset.defaultCharset());
                        ChannelFuture wf = future.channel()
                                .writeAndFlush(buffer);
                        future.channel().flush();
                    } else {
                        Throwable cause = future.cause();
                        cause.printStackTrace();
                    }
                }
            });
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully().sync();
        }
    }
}